package com.okilo.online.app.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import com.okilo.online.app.R
import com.okilo.online.app.base.app.OkiloActStackManager
import com.okilo.online.app.databinding.OkiloRootViewBinding
import com.okilo.online.app.act.OkiloLaunchAct
import com.okilo.online.app.dialog.LoadingConfig
import com.okilo.online.app.tools.OkiloDensityUtil
import com.okilo.online.app.tools.OkiloTitleBarUtil
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.manager.OkiloBackPressHandler
import com.okilo.online.app.tools.manager.OkiloFragmentNavigator
import com.okilo.online.app.tools.manager.OkiloKeyboardManager
import com.okilo.online.app.tools.manager.OkiloLoadingManager
import com.okilo.online.app.tools.manager.OkiloTitleBarManager
import com.okilo.online.app.tools.manager.OkiloToastManager

/**
 * 基类 Activity
 */
abstract class OkiloBaseAct: AppCompatActivity(), IOkiloBaseView {

    // 属性声明
    private lateinit var rootViewBinding: OkiloRootViewBinding

    /** 管理器实例 */
    private lateinit var titleBarManager: OkiloTitleBarManager
    private lateinit var keyboardManager: OkiloKeyboardManager
    private lateinit var fragmentNavigator: OkiloFragmentNavigator
    private lateinit var backPressHandler: OkiloBackPressHandler
    private lateinit var loadingManager: OkiloLoadingManager

    /* 原有配置变量（保持兼容性） */
    private var isInterceptBack = false
    private var isHideSoftInput = true
    private var mExitTips = "Press again to exit the app"
    private var isBackExit = false
    private var exitTime: Long = 0

    // 获取页面名称，子类必须实现
    protected abstract val pageName: String
    // 是否启用页面埋点（默认启用）
    protected open val enablePageTrack: Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (savedInstanceState != null && this::class.java.simpleName != OkiloLaunchAct::class.java.simpleName) {
            onIntent(OkiloLaunchAct::class.java)
            return
        }

        OkiloTitleBarUtil.transparentStatusBar(this)
        OkiloTitleBarUtil.setStatusBarLightMode(this, true)

        setContentView(createOkiloContentView())
        initializeOkiloViews()
        setupOkiloEventListeners()
        loadOkiloData()
    }

    override fun onDestroy() {
        super.onDestroy()
        loadingManager.dismissLoading()
    }

    override fun onBackPressed() {
        if (!backPressHandler.onBackPressed()) {
            super.onBackPressed()
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        // 委托给键盘管理器处理触摸事件
        keyboardManager.dispatchTouchEvent(ev)
        return super.dispatchTouchEvent(ev)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (isBackExit) {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    showOkiloToast(mExitTips)
                    exitTime = System.currentTimeMillis()
                } else {
                    OkiloActStackManager.finishAllActivity()
                }
            } else {
                onBackAction()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    // region 抽象方法 - 子类必须实现
    protected abstract fun createOkiloContentView(): View?

    protected abstract fun initializeOkiloViews()

    protected abstract fun setupOkiloEventListeners()

    protected abstract fun loadOkiloData()

    // 初始化方法
    override fun setContentView(rootView: View?) {
        // 初始化根视图绑定
        rootViewBinding = OkiloRootViewBinding.inflate(layoutInflater)
        // 初始化管理器
        initializeManagers()

        // 设置状态栏padding
        val leftPadding = OkiloDensityUtil.dp2px(16f)
        val topPadding = OkiloDensityUtil.dp2px(10f)
        val bottomPadding = OkiloDensityUtil.dp2px(6f)
        rootViewBinding.rootTitleBar.setPadding(leftPadding, OkiloTitleBarUtil.getStatusBarHeight() + topPadding, leftPadding, bottomPadding)

        // 添加内容视图
        if (rootView != null) {
            rootViewBinding.rootContainer.addView(rootView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        }

        // 设置返回按钮监听
        setupBackButtonListener()

        // 默认隐藏TitleBar
        titleBarManager.setTitleBarVisibility(View.GONE)

        // 调用父类的setContentView
        super.setContentView(rootViewBinding.root)
    }

    /**
     * 初始化所有管理器
     */
    private fun initializeManagers() {
        titleBarManager = OkiloTitleBarManager(rootViewBinding)
        keyboardManager = OkiloKeyboardManager(this)
        fragmentNavigator = OkiloFragmentNavigator(supportFragmentManager)
        loadingManager = OkiloLoadingManager(this)
        backPressHandler = OkiloBackPressHandler(this)

        // 同步配置到管理器
        syncConfigToManagers()
    }

    /**
     * 同步配置到各个管理器
     */
    private fun syncConfigToManagers() {
        backPressHandler.setInterceptBack(isInterceptBack)
        backPressHandler.setDoubleBackToExitEnabled(isBackExit)
        backPressHandler.setExitTips(mExitTips)
        keyboardManager.setHideOnTouchOutside(isHideSoftInput)
    }

    /**
     * 设置返回按钮点击监听器
     */
    private fun setupBackButtonListener() {
        setBackButtonClickListener(object : OkiloOnSingleClickListener() {
            override fun onSingleClick(v: View?) {
                onBackAction()
            }
        })
    }

    // IBaseView 接口实现
    override fun getContext(): Context {
        return this
    }

    override fun showOkiloLoading() {
        showOkiloLoading(getString(R.string.okilo_loading))
    }

    fun showOkiloLoading(msg: String = "") {
        loadingManager.showLoading(msg)
    }

    fun showOkiloLoading(isTouchOut: Boolean, isCancel: Boolean, msg: String = "") {
        val config = LoadingConfig(
            message = msg,
            isCancelable = isCancel,
            isTouchOutsideCancelable = isTouchOut
        )
        loadingManager.showLoading(config)
    }

    override fun hideOkiloLoading() {
        loadingManager.dismissLoading()
    }

    /**
     * toast
     * @param s
     */
    override fun showOkiloToast(s: String?) {
        OkiloToastManager.showShortText(this, s)
    }

    /**
     * 设置退出程序提示语
     */
    fun setExitTips(tips: String) {
        this.mExitTips = tips
        backPressHandler.setExitTips(tips)
    }

    /**
     * 是否拦截返回按钮
     */
    fun isInterceptBack(isBackExit: Boolean) {
        this.isInterceptBack = isBackExit
        backPressHandler.setInterceptBack(isBackExit)
    }

    /**
     * 点击外部是否需要隐藏软键盘
     */
    fun isHideSoftInputClickTouchOut(isTouchOut: Boolean) {
        this.isHideSoftInput = isTouchOut
        keyboardManager.setHideOnTouchOutside(isTouchOut)
    }

    /**
     * @功能描述：是否连续两次返回退出
     */
    fun setBackExit(isBackExit: Boolean) {
        this.isBackExit = isBackExit
        backPressHandler.setDoubleBackToExitEnabled(isBackExit)
    }

    /**
     * 页面跳转（不带参数）
     *
     * @param T
     */
    open fun onIntent(T: Class<*>?) {
        startActivity(Intent(this, T))
    }

    /**
     * 页面跳转（带参数）
     *
     * @param T
     * @param bundle
     */
    open fun onIntent(T: Class<*>?, bundle: Bundle?) {
        val intent = Intent(this, T)
        if (bundle != null) intent.putExtras(bundle)
        startActivity(intent)
    }

    /* 隐藏键盘 */
    fun onHideSoftInput(v: View) {
        keyboardManager.hideSoftInputFrom(v.windowToken)
    }

    /**
     * 隐藏软键盘
     */
    fun onHideSoftInput() {
        keyboardManager.hideSoftInput()
    }

    /* 显示键盘 */
    fun onShowSoftInput(v: View) {
        keyboardManager.showSoftInput(v)
    }

    /* 返回 */
    open fun onBackAction() {
        if (!isInterceptBack) { // 不拦截，直接返回
            finish()
        }
    }

    /**
     * 获取TitleBar管理器（用于链式调用）
     */
    protected fun getTitleBarManager(): OkiloTitleBarManager {
        return titleBarManager
    }

    /**
     * 获取TitleBar binding
     */
    protected fun getRootViewBinding(): OkiloRootViewBinding {
        return rootViewBinding
    }

    /**
     * 获取Fragment导航器
     */
    protected fun getFragmentNavigator(): OkiloFragmentNavigator {
        return fragmentNavigator
    }

    /**
     * 获取键盘管理器
     */
    protected fun getKeyboardManager(): OkiloKeyboardManager {
        return keyboardManager
    }

    /**
     * 获取返回键处理器
     */
    protected fun getBackPressHandler(): OkiloBackPressHandler {
        return backPressHandler
    }

    /**
     * 获取加载管理器
     */
    protected fun getLoadingManager(): OkiloLoadingManager {
        return loadingManager
    }

    /**
     * 设置右侧按钮点击监听器
     */
    protected fun setRightButtonClickListener(listener: View.OnClickListener) {
        titleBarManager.setRightButtonClickListener(listener)
    }

    /**
     * 设置返回按钮点击监听器（覆盖默认行为）
     */
    protected fun setBackButtonClickListener(listener: View.OnClickListener) {
        titleBarManager.setBackButtonClickListener(listener)
    }
}